<template>
  <ElDrawer v-model="opened" :title="formType" direction="rtl">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else ref="formRef" :model="form" :rules="rules" :disabled="isView" label-position="right" :label-width="80">
      <ElFormItem label="字典类型" prop="type">
        <ElInput placeholder="请输入字典类型" v-model="form.type" />
      </ElFormItem>
      <ElFormItem label="描述" prop="description">
        <ElInput placeholder="请输入字典描述" v-model="form.description" />
      </ElFormItem>
      <ElFormItem label="系统字典" prop="isSystem">
        <ElRadioGroup v-model="form.isSystem">
          <ElRadio v-for="item in IsSystemEnum" :label="item.value" :key="item.value">{{ item.label }}</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="备注" prop="remark">
        <ElInput placeholder="请输入备注" v-model="form.remark" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton v-if="isView" @click="onCancelClicked">关闭</ElButton>
      <ElButton v-else @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>
<script setup lang="ts">
import { reactive, ref, unref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { FormType } from '@/enums'
import { checkExist, getDict, addDict, updateDict } from '@api/uc/dict'
import { Dict } from '@api/uc/dict/interface'
import { IsSystemEnum } from './dict'
import { validateCode } from '@/utils/validator'
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<Dict.Form>>({})
const opened = ref(false)
const loading = ref(true)
const emit = defineEmits(['success'])

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

// 权限校验
const validate = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback()
  }
  checkExist({ id: form.value.id, type: value }).then(resp => {
    if (resp.data) {
      callback(new Error('该字典项已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  type: [
    { required: true, message: '请输入类型', trigger: 'blur' },
    { max: 30, message: '类型最大长度 30', trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' },
    { max: 100, message: '描述最大长度 100', trigger: 'blur' }
  ],
  remark: [{ max: 255, message: '备注最大长度 255', trigger: 'blur' }]
})

// 打开表单
async function open(type: FormType, id?: string) {
  formType.value = type
  opened.value = true
  if (isAdd.value) {
    loading.value = false
    form.value = { isSystem: '0' }
  } else {
    try {
      const { data } = await getDict(id!)
      loading.value = false
      form.value = data
    } finally {
      loading.value = false
    }
  }
  formRef.value?.clearValidate()
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const params = Object.assign({}, unref(form))
    if (isAdd.value) {
      addDict(params).then(() => {
        success()
        sendSuccess()
        close()
      })
    } else {
      updateDict(params).then(() => {
        success()
        sendSuccess()
        close()
      })
    }
  })
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
function sendSuccess() {
  emit('success')
}

defineExpose({
  open,
  close
})
</script>
